﻿using System.Collections.Generic;
using Downloader.Domain;
using Downloader.Framework.Queries;
using Downloader.Infrastructure;
using Downloader.Web.Controllers.ViewModels;
using SharpArch.NHibernate;

namespace Downloader.Web.Controllers.Queries
{
    public class CategoryListQuery : NHibernateQuery, ICategoryListQuery
    {



        public RecordList<CategoryViewModel> GetList(int page, int size)
        {
            var query = Session.QueryOver<Category>().Where(c => c.Parent == null).OrderBy(x => x.Name).Asc;
            var count = query.ToRowCountQuery();
            var totalCount = count.FutureValue<int>();

            var firstResult = (page - 1) * size;
            var recordList = new RecordList<CategoryViewModel>();
            recordList.Data = new List<CategoryViewModel>();
            var model = query.Skip(firstResult).Take(size).Future();
            CategoryViewModel temp = null;
            foreach (var m in model)
            {
                temp = new CategoryViewModel(m);
                recordList.Data.Add(temp);
            }
            recordList.PageIndex = page;
            recordList.PageSize = size;
            recordList.RecordCount = totalCount.Value;
            return recordList;
        }




        public IList<Category> GetMenu()
        {
            var query = Session.QueryOver<Category>().Where(c => c.Parent == null).OrderBy(x => x.Sequence).Asc;
            var model = query.List();
            return model;
        }
        public Category GetSingle(string categoryName)
        {
            var query =
                Session.QueryOver<Category>().Where(c => c.Name == categoryName);
            var model = query.SingleOrDefault();
            return model;
        }

        public IList<CategoryViewModel> GetSubList(int parentId)
        {
            var reusltList = new List<CategoryViewModel>();
            var query = Session.QueryOver<Category>()
                               .JoinQueryOver(c => c.Parent)
                               .Where(k => k.Id == parentId)
                               .OrderBy(x => x.Sequence).Asc;
            var list = query.List();
            CategoryViewModel temp = null;
            foreach (var m in list)
            {
                temp = new CategoryViewModel(m);
                temp.IsSub = true;
                reusltList.Add(temp);
            }
            return reusltList;
        }



    }
}